package com.myproject.myblogserver.service.impl;

import com.myproject.myblogserver.entity.VerificationCode;
import com.myproject.myblogserver.mapper.VerificationCodeMapper;
import com.myproject.myblogserver.service.IVerificationCodeService;
import com.myproject.myblogserver.utils.MailUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 验证码表 服务实现类
 * </p>
 *
 * @author jiangweike
 * @since 2025-01-05
 */
@Service
public class VerificationCodeServiceImpl extends ServiceImpl<VerificationCodeMapper, VerificationCode>
        implements IVerificationCodeService {
    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private VerificationCodeMapper verificationCodeMapper;

    // 验证码有效期（分钟）
    private static final int CODE_EXPIRE_MINUTES = 100;

    @Override
    public VerificationCode send(String email) {
        verificationCodeMapper.updateIsDeletedByEmail(email);

        // 生成验证码
        String code = generateCode();

        // 保存验证码
        var verificationCode = new VerificationCode();
        verificationCode.setEmail(email);
        verificationCode.setCode(code);
        verificationCode.setExpireTime(LocalDateTime.now().plusMinutes(CODE_EXPIRE_MINUTES));

        verificationCodeMapper.insert(verificationCode);

        // 发送邮件
        mailUtil.send(email, code);
        return verificationCode;
    }

    private String generateCode() {
        var random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }
}
